package com.example.util.sql;

import org.apache.tomcat.jni.User;

import java.lang.reflect.Field;
import java.util.*;

public class SqlGenerator {

    /**
     * 生成INSERT语句
     * @param tableName 表名
     * @param entity 实体对象
     * @return INSERT SQL语句和参数列表
     */
    public static SqlResult generateInsert(String tableName, Object entity) {
        if (tableName == null || tableName.trim().isEmpty() || entity == null) {
            throw new IllegalArgumentException("表名和实体对象不能为空");
        }

        List<Object> params = new ArrayList<>();
        StringBuilder columns = new StringBuilder();
        StringBuilder placeholders = new StringBuilder();

        Field[] fields = entity.getClass().getDeclaredFields();

        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(entity);

                // 忽略null值
                if (value != null) {
                    if (columns.length() > 0) {
                        columns.append(", ");
                        placeholders.append(", ");
                    }
                    columns.append(camelToSnake(field.getName()));
                    placeholders.append("?");
                    params.add(value);
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("获取字段值失败", e);
        }

        if (columns.length() == 0) {
            throw new IllegalArgumentException("实体对象所有字段都为空");
        }

        String sql = String.format("INSERT INTO %s (%s) VALUES (%s)",
                tableName, columns, placeholders);

        return new SqlResult(sql, params);
    }

    /**
     * 生成UPDATE语句
     * @param tableName 表名
     * @param entity 实体对象
     * @param whereConditions WHERE条件（字段名列表）
     * @return UPDATE SQL语句和参数列表
     */
    public static SqlResult generateUpdate(String tableName, Object entity, List<String> whereConditions) {
        return generateUpdate(tableName, entity, whereConditions, null);
    }

    public static SqlResult generateUpdateById(String tableName, Object entity,String id) {
        return generateUpdate(tableName, entity, Collections.singletonList(id), null);
    }

    /**
     * 生成UPDATE语句（带排除字段）
     * @param tableName 表名
     * @param entity 实体对象
     * @param whereConditions WHERE条件字段
     * @param excludeFields 排除的字段
     * @return UPDATE SQL语句和参数列表
     */
    public static SqlResult generateUpdate(String tableName, Object entity,
                                           List<String> whereConditions, List<String> excludeFields) {
        if (tableName == null || tableName.trim().isEmpty() || entity == null) {
            throw new IllegalArgumentException("表名和实体对象不能为空");
        }

        if (whereConditions == null || whereConditions.isEmpty()) {
            throw new IllegalArgumentException("WHERE条件不能为空");
        }

        List<Object> params = new ArrayList<>();
        StringBuilder setClause = new StringBuilder();

        Field[] fields = entity.getClass().getDeclaredFields();
        Set<String> whereSet = new HashSet<>(whereConditions);
        Set<String> excludeSet = excludeFields != null ? new HashSet<>(excludeFields) : new HashSet<>();

        try {
            // 构建SET子句
            for (Field field : fields) {
                String fieldName = field.getName();
                String columnName = camelToSnake(fieldName);

                // 跳过WHERE条件字段和排除字段
                if (whereSet.contains(fieldName) || excludeSet.contains(fieldName)) {
                    continue;
                }

                field.setAccessible(true);
                Object value = field.get(entity);

                // 只处理非空值
                if (value != null) {
                    if (setClause.length() > 0) {
                        setClause.append(", ");
                    }
                    setClause.append(columnName).append(" = ?");
                    params.add(value);
                }
            }

            // 构建WHERE子句
            StringBuilder whereClause = new StringBuilder();
            Field[] fieldList=entity.getClass().getDeclaredFields();
            for (Field field : fieldList) {
                String fieldName = field.getName();
                System.out.println(fieldName);
            }
            for (String whereField : whereConditions) {
                Field field = entity.getClass().getDeclaredField(whereField);
                field.setAccessible(true);
                Object value = field.get(entity);

                if (value == null) {
                    throw new IllegalArgumentException("WHERE条件字段 '" + whereField + "' 值不能为空");
                }

                if (whereClause.length() > 0) {
                    whereClause.append(" AND ");
                }
                whereClause.append(camelToSnake(whereField)).append(" = ?");
                params.add(value);
            }

            if (setClause.length() == 0) {
                throw new IllegalArgumentException("没有可更新的字段");
            }

            String sql = String.format("UPDATE %s SET %s WHERE %s",
                    tableName, setClause, whereClause);

            return new SqlResult(sql, params);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("生成UPDATE语句失败", e);
        }
    }

    /**
     * 驼峰命名转下划线命名
     */
    private static String camelToSnake(String camelCase) {
        return camelCase.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
    }


}
